package cn.lliiooll.util;

import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Utils {
    private static final Charset UTF_8 = StandardCharsets.UTF_8;

    /**
     * 将注释转换为键
     *
     * @param file 配置文件
     */
    public static String parseNotes2Key(File file) {
        List<String> lines = Utils.readLines(file);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lines.size(); i++) {
            String line = lines.get(i);
            String s = line.replaceAll(" ", "");
            if (s.startsWith("#")) {
                sb.append(line.replaceFirst("# ", "\"^") + "\": ''");
            } else sb.append(line);
            sb.append("\n");
        }
        return sb.toString();
    }

    /**
     * 将特定键还原为注释
     *
     * @param file 配置文件
     */
    public static void parseKey2Notes(File file) {
        List<String> lines = Utils.readLines(file);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lines.size(); i++) {
            String line = lines.get(i);
            String s = line.replaceAll(" ", "");
            if (s.startsWith("^")) {
                sb.append(line.split(":")[0].replaceFirst("\\^", "# "));
            } else if (s.startsWith("'^")) {
                sb.append(line.split(":")[0].replaceFirst("'\\^", "# ").replace("'", ""));
            } else if (s.startsWith("\"^")) {
                sb.append(line.split(":")[0].replaceFirst("\"\\^", "# ").replace("\"", ""));
            } else sb.append(line);
            sb.append("\n");
        }
        Utils.writeStr(file, Hutool.toString(sb.toString()));
    }

    public static List<String> readLines(File file) {
        List<String> lines = new ArrayList<>();
        try {
            BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(file), Utils.UTF_8));
            String line = "";
            while ((line = r.readLine()) != null) {
                lines.add(line);
            }
            r.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lines;
    }

    public static void writeStr(File file, String str) {
        try {
            FileOutputStream fw = new FileOutputStream(file);
            fw.write(str.getBytes(Utils.UTF_8));
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static boolean isNumeric(String str) {
        return !Hutool.isEmpty(str) && str.matches("-?[0-9]*");
    }

    public static boolean isPlayer(CommandSender sender) {
        return sender instanceof Player;
    }
}
